﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Acme.Sakila.TestSite.Objects;
using nHydrate.EFCore.DataAccess;
using Acme.Sakila.EFDAL;
using Acme.Sakila.EFDAL.Entity;

namespace Acme.Sakila.TestSite
{
	public partial class CustomerList : BasePage
	{
		#region Page Events

		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);
			grdItem.RowDataBound += new GridViewRowEventHandler(grdItem_RowDataBound);
			this.PagingControl1.ObjectSingular = "Customer";
			this.PagingControl1.ObjectPlural = "Customers";
			this.PagingControl1.RecordsPerPageChanged += new EventHandler(PagingControl1_RecordsPerPageChanged);
		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);
			if (!this.IsPostBack)
			{
				this.Populate();
			}
		}

		#endregion

		#region Methods

		private void Populate()
		{
			using (var context = new SakilaEntities(Utils.ContextStartup))
			{
				var paging = new Paging(this.PagingControl1.PageIndex, this.PagingControl1.RecordsPerPage);
				var customerCollection = context.customer.GetPagedResults(x => x.customer_id, paging);
				this.PagingControl1.ItemCount = paging.RecordCount;
				grdItem.DataSource = customerCollection;
				grdItem.DataBind();
				SessionHelper.LastCustomerListSearch = this.Request.Url.AbsoluteUri;
			}
		}

		#endregion

		#region Event Handlers

		private void grdItem_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				var theCustomer = e.Row.DataItem as Acme.Sakila.EFDAL.Entity.customer;
				var linkEdit = (HyperLink)e.Row.FindControl("linkEdit");
				var linkRentals = (HyperLink)e.Row.FindControl("linkRentals");
				var linkPayments = (HyperLink)e.Row.FindControl("linkPayments");
				
				linkEdit.NavigateUrl = "/CustomerItem.aspx?id=" + theCustomer.customer_id;
				linkRentals.NavigateUrl = "/RentalList.aspx?customerid=" + theCustomer.customer_id;
				linkPayments.NavigateUrl = "/PaymentList.aspx?customerid=" + theCustomer.customer_id;
			}
		}

		private void PagingControl1_RecordsPerPageChanged(object sender, EventArgs e)
		{
			var query = new URL(this.Request.Url.AbsoluteUri);
			query.Parameters.SetValue("rpp", PagingControl1.RecordsPerPage.ToString());
			query.Parameters.SetValue("po", "1");
			this.Response.Redirect(query.ToString());
		}

		#endregion

	}
}
